﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;

namespace PasswdGen.Util
{
    public class GenSfzCode
    {
        static Random random = new Random();

        public static string GenerateIDNumber()
        {
            // 随机生成地区码
            //string regionCode = random.Next(110000, 650000).ToString();
            int index = random.Next(0, AreaCodeHelper.provinceCodes.Length);
            string regionCode = AreaCodeHelper.provinceCodes[index] +"0000";

            // 随机生成出生日期（格式：yyyy-MM-dd）
            DateTime birthDate = GenerateRandomBirthDate();

            // 随机生成顺序码（范围：000-999）
            string sequenceCode = random.Next(0, 1000).ToString().PadLeft(3, '0');

            // 计算校验码
            string checkCode = CalculateCheckCode(regionCode, birthDate, sequenceCode);

            // 构建身份证号
            string idNumber = $"{regionCode}{birthDate.ToString("yyyyMMdd")}{sequenceCode}{checkCode}";

            return idNumber;
        }

        public static DateTime GenerateRandomBirthDate()
        {
            DateTime startDate = new DateTime(1950, 1, 1);
            int totalDays = (DateTime.Today - startDate).Days;
            int randomDays = random.Next(totalDays);

            DateTime birthDate = startDate.AddDays(randomDays);
            return birthDate;
        }

        public static string CalculateCheckCode(string regionCode, DateTime birthDate, string sequenceCode)
        {
            string id17 = $"{regionCode}{birthDate.ToString("yyyyMMdd")}{sequenceCode}";

            int[] factors = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            string[] checkCodes = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };

            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                int num = int.Parse(id17[i].ToString());
                sum += num * factors[i];
            }

            int remainder = sum % 11;
            string checkCode = checkCodes[remainder];

            return checkCode;
        }


        public string GetGenderFromIdCard()
        {
            return GetNameHelper.GetWomanName();
        }

        /// <summary>
        /// 通过身份证获取性别
        /// </summary>
        /// <param name="idCardNumber"></param>
        /// <returns></returns>
        public static string GetGenderFromIdCard(string idCardNumber)
        {
            string genderCode = idCardNumber.Substring(idCardNumber.Length - 2, 1);
            int code = int.Parse(genderCode);
            return code % 2 == 0 ? "女" : "男";
        }


        /// <summary>
        /// 通过身份证获取年龄
        /// </summary>
        /// <param name="idNumber"></param>
        /// <returns></returns>
        public static string GetAgeFromIdCard(string idNumber)
        {
            return null;

        }

        /// <summary>
        /// 通过身份证获生日
        /// </summary>
        /// <param name="idCardNumber"></param>
        /// <returns></returns>
        public static string GetBirthdayFromIdCard(string idCardNumber)
        {
            string birthdayPart = idCardNumber.Substring(6, 8);
            string year = birthdayPart.Substring(0, 4);
            string month = birthdayPart.Substring(4, 2);
            string day = birthdayPart.Substring(6, 2);
            return $"{year}-{month}-{day}";
        }

        /// <summary>
        /// 所在行政区
        /// </summary>
        /// <param name="idCardNumber"></param>
        /// <returns></returns>
        public static string GetProvinceCodeFromIdCard(string idCardNumber)
        {
            string provinceCode = idCardNumber.Substring(0, 2);
            // 这里可以编写对应的代码将省份代码转换为省份名称，根据实际需求自行实现
            // 示例中直接返回省份代码
            
            return provinceCode;
        }

        public static string GetProvinceNameFromIdCard(string idCardNumber)
        {
            string provinceCode = idCardNumber.Substring(0, 2);            
            return AreaCodeHelper.ContrastTable(provinceCode); ;
        }

        public static string GetProvinceByIDCard(string idCardNumber)
        {
            string provinceCode = idCardNumber.Substring(0, 2);
            // 这里可以编写对应的代码将省份代码转换为省份名称，根据实际需求自行实现
            // 示例中直接返回省份代码

            return AreaCodeHelper.GetProvinceByIDCard(idCardNumber);
        }
        


        public enum Gender
        {
            Male,
            Female
        }

        public static Gender GenerateRandomGender(Random random)
        {
            return (Gender)random.Next(2); // 0 表示 Male，1 表示 Female
        }



        /// <summary>
        /// 根据身份证获取年龄
        /// </summary>
        /// <param name="idCardNumber"></param>
        /// <returns></returns>
        public static int GetAgeFromIdBirthday(string idCardNumber)
        {
            //string birthdayPart = idCardNumber.Substring(6, 8);
            //string yearStr = birthdayPart.Substring(0, 4);
            //string monthStr = birthdayPart.Substring(4, 2);
            //string dayStr = birthdayPart.Substring(6, 2);

            //int year = int.Parse(yearStr);
            //int month = int.Parse(monthStr);
            //int day = int.Parse(dayStr);

            //DateTime birthday = new DateTime(year, month, day);


            // 或者用如下方法
            string dateString = GetBirthdayFromIdCard(idCardNumber);
            string format = "yyyy-MM-dd";

            // Parse the date string into a DateTime object
            DateTime birthday = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

            return CalculateAge(birthday);
        }


        /// <summary>
        /// 通过日期计算年龄
        /// </summary>
        /// <param name="birthday"></param>
        /// <returns></returns>
        public static int CalculateAge(DateTime birthday)
        {
            DateTime today = DateTime.Today;

            int age = today.Year - birthday.Year;

            if (today.Month < birthday.Month || (today.Month == birthday.Month && today.Day < birthday.Day))
            {
                age--;
            }

            return age;
        }
    }
}
